<?php

namespace Izqut\Membership\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Membership extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'description',
        'price',
        'duration_days',
        'is_active',
        'features',
        'sort_order',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'duration_days' => 'integer',
        'is_active' => 'boolean',
        'features' => 'array',
        'sort_order' => 'integer',
    ];

    /**
     * Get all user memberships for this plan
     */
    public function userMemberships(): HasMany
    {
        return $this->hasMany(UserMembership::class);
    }

    /**
     * Check if membership is active
     */
    public function isActive(): bool
    {
        return $this->is_active;
    }

    /**
     * Check if membership is VIP
     */
    public function isVip(): bool
    {
        return $this->slug === config('membership.vip_slug', 'vip');
    }

    /**
     * Check if membership is perpetual (lifetime)
     */
    public function isPerpetual(): bool
    {
        return is_null($this->duration_days);
    }

    /**
     * Get formatted price
     */
    public function getFormattedPriceAttribute(): string
    {
        return number_format($this->price, 2);
    }

    /**
     * Scope: only active memberships
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope: only VIP memberships
     */
    public function scopeVip($query)
    {
        return $query->where('slug', config('membership.vip_slug', 'vip'));
    }

    /**
     * Scope: ordered by sort_order
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }
}
